package imoney.server;

import java.util.ArrayList;

import imoney.client.rpc.GroupService;
import imoney.server.util.DataStoreManager;
import imoney.server.util.IDsManager;
import imoney.shared.CookieBuilderShared;
import imoney.shared.exception.AlreadyExistingException;
import imoney.shared.exception.NoSuchPersonException;
import imoney.shared.exception.PositionOutOfDateException;
import imoney.shared.model.DebtManager;
import imoney.shared.model.Group;
import imoney.shared.model.Person;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GroupServiceImpl extends RemoteServiceServlet implements GroupService {

	/**
	 * The date of the last modification requiring new version.
	 */
	private static final long serialVersionUID = 31052011L;

	public ArrayList<Group> getGroups(String cookieValue) throws NoSuchPersonException, PositionOutOfDateException {
		ArrayList<Group> groups = null;
		int position = CookieBuilderShared.readPosition(cookieValue);
		String googleID = CookieBuilderShared.readUserId(cookieValue);
		Person pers = UserServlet.getPerson(position, googleID, getServletContext());
		groups = DataStoreManager.getGroupList(pers.getGroupsList());
		// TODO remove the dirty fix below once migrated to high replication ds who hopefully should have resolved the issue
		ArrayList<Group> result = new ArrayList<Group>();
		for (Group gp : groups) {
			ArrayList<String> newinstance = new ArrayList<String>(gp.getMembres());
			result.add(new Group(newinstance, gp.getName(), gp.getBanker()));
		}
		return result;
	}

	@Override
	public Group saveGroup(String groupName, ArrayList<String> people)
			throws AlreadyExistingException, NoSuchPersonException {
		// save the group and its debt manager at the same time
		Group group = new Group(people, groupName, people.get(0));
		DataStoreManager.registerAndMakePersistent(group);
		ArrayList<Integer> ids = IDsManager.getIdList(people);
		DebtManager debtmng = new DebtManager(group.getId(), ids);
		// this id will be reset during transaction with datastore
		// it is here only to do an availability pre-check. not very consistent.
		debtmng.setId(group.getId());
		DataStoreManager.registerAndMakePersistent(debtmng);
		// add the group to each individual included in it
		for(String pseudo : people) {
			Person pers = DataStoreManager.getPersonByPseudo(pseudo);
			pers.addGroup(groupName);
		}
		// close the persistence manager to persist changes
		DataStoreManager.closePM();
		// TODO remove this fix after moving to high replication ?
		// fixing list type back to java.util.ArrayList
		group.setMembres(new ArrayList<String>(group.getMembres()));
		return group;
	}

}
